<template>
  <NModal :show="showModal">
    <NCard style="width: 400px" title="读取流程" :bordered="false" closable @close="onClose">
      <NSpace vertical>
        <NSpace vertical>
          <label>选择流程：</label>
          <NSelect
            v-model:value="state.definitionKey"
            style="margin-bottom: 8px"
            :options="state.definitionOptions"
            @change="onDefinitionChange"
          />
          <label>选择版本：</label>
          <NSelect v-model:value="state.deploymentId" :options="state.versionOptions" />
        </NSpace>
      </NSpace>
      <template #footer>
        <NSpace justify="end" style="margin-top: 10px">
          <n-button size="small" @click="onClose">关闭</n-button>
          <n-button size="small" type="info" :disabled="!state.deploymentId" @click="onSelect">
            读取
          </n-button>
        </NSpace>
      </template>
    </NCard>
  </NModal>
</template>

<script setup lang="ts">
  import { reactive, onMounted, computed } from 'vue'
  import { NModal, NCard, NSelect, NSpace, useMessage } from 'naive-ui'
  import { processApi } from '@/api/modules/process'

  const props = defineProps<{ show: boolean }>()
  const emits = defineEmits(['close', 'select'])

  const showModal = computed(() => props.show)

  const message = useMessage()

  const state = reactive({
    data: [] as any[],

    definitionKey: '',
    definitionOptions: [] as any[],

    deploymentId: '',
    versionOptions: [] as any[]
  })

  const findDefinition = () => {
    processApi.findDefList().then((resp) => {
      if (resp.success) {
        state.data = resp.data
        for (let key in state.data) {
          state.definitionOptions.push({ label: `${state.data[key][0].name} (${key})`, value: key })
        }
      }
    })
  }
  const onDefinitionChange = (value: string) => {
    const versionData = state.data[value]
    state.versionOptions = versionData.map((v) => {
      return { label: `V${v.version}`, value: v.deploymentId }
    })
  }

  onMounted(findDefinition)

  const onClose = () => {
    console.log('onClose')
    emits('close', false)
  }

  const onSelect = () => {
    processApi.findXml(state.deploymentId).then((resp) => {
      if (resp.success) {
        emits('select', resp.data)
      } else {
        message.error('资源获取失败')
        console.error(resp.message)
      }
    })
  }
</script>

<style lang="scss" scoped></style>
